import React, { Component } from 'react'
import { inject, observer } from 'mobx-react';
import { hashHistory } from 'react-router';
import { Toast, ListView, Picker, Flex, SegmentedControl, List, Button, Popup, Icon, DatePicker, TextareaItem, InputItem, Stepper } from 'antd-mobile'
import { createForm } from 'rc-form';
import Top from 'components/top'
import Ajax from 'lib/Ajax'
import Msg from 'mixin/msg'

const Item = List.Item;
const Brief = Item.Brief;
const pageName = 'interviewMsg';

const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
let maskProps;
if (isIPhone) {
  // Note: the popup content will not scroll.
  maskProps = {
    onTouchStart: e => e.preventDefault(),
  };
}

@inject('appStore', 'languageStore')
@observer
class ModuleName extends Msg {
	constructor(props) {
    super(props);
		this.searchOption = {
			interviewId: this.props.params.id
		}
		this.msgApi = '/interview/get';
    this.state = Object.assign({
      selectedIndex: '详细描述'
    }, this.state)
  }

  buy = ()=>{
    Popup.show(<div>
      <BuyModule
        onClose={this.onClose}
        data={this.state.msgData}
      />
    </div>, { animationType: 'slide-up', maskProps, maskClosable: false });
  };

  onClose = (sel) => {
    this.setState({ sel });
    Popup.hide();
  };

  addline = () => {
    Ajax({
      url: '/chat/addline',
      data: {
        "userId": this.props.appStore.userData.userId,
        "teacherId": this.state.msgData.teacherDTO.teacherId
      },
      success: function(result){
        hashHistory.push('/chat/' + result.chatLineId);
      },
      error: function(error){
        Toast.info(error||'请求失败');
        self.props.onClose();
      }
    });
  }

  render() {
    const pageData = this.props.languageStore.getPageData(pageName);
    const { teacherDTO, introduction, title, readCount, saleCount, explainStr, price } = this.state.msgData;
    const { imgBaseUrl } = this.props.appStore;
    return (
    	<div className={pageName}>
        <Top
          title={pageData.title}
        />
        <div className={`${pageName}-content`}>
          <div className="interview-temp">
            <div className="img-box">
							<img src={`${imgBaseUrl}${teacherDTO&&teacherDTO.coverImg}`} alt="" className="coverImg" />
							<p className="name">{ teacherDTO&&teacherDTO.name||"" }</p>
							<p className="zhiwei">{ teacherDTO&&teacherDTO.major||"" }</p>
						</div>
            <div className="b-s">
              <h3>{ title }</h3>
              <div className="desc">
                <span className="red">￥{price}/小时</span>
                <span className="fr">已购 {saleCount}</span>
              </div>
            </div>
            <div className="blank" style={{height: '.2rem'}}></div>
            <div style={{padding: '.2rem 80px 0'}}>
              <SegmentedControl values={['详细描述', '服务说明']} onValueChange={(value)=>{
                this.setState({
                  selectedIndex: value
                });
              }}/>
            </div>
            <div className="desc-con">
              {this.state.selectedIndex == '详细描述'?<div dangerouslySetInnerHTML={{__html: introduction}}></div>:<div dangerouslySetInnerHTML={{__html: explainStr}}></div>}
            </div>
            <div className="inter-teacher">
              <List>
                <Item
                  arrow="horizontal"
                  thumb={`${imgBaseUrl}${teacherDTO&&teacherDTO.coverImg}`}
                  multipleLine
                  onClick={() => {}}
                >
                  {teacherDTO&&teacherDTO.name} <Brief>{teacherDTO&&teacherDTO.school} {teacherDTO&&teacherDTO.major}</Brief>
                </Item>
              </List>
            </div>
            <div className="blank" style={{height: '.2rem'}}></div>
            <div className="inter-footer">
              <Flex>
                <Flex.Item>
                  <div className="btn">
                    <Button type="ghost" onClick={this.addline} inline size="small" style={{ marginRight: '0.08rem' }}>联系咨询师</Button>
                  </div>
                </Flex.Item>
                <Flex.Item>
                  <div className="btn btn-buy" onClick={this.buy}>购买服务</div>
                </Flex.Item>
              </Flex>
            </div>
          </div>
        </div>
    	</div>
    )
  }
}

module.exports = ModuleName

class buyModuleComp extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      moneyfocused: false,
      hour: 1
    }
  }

  submit = () => {
    const self = this;
    const { interviewId, saleCount } = this.props.data;
    const option = self.props.form.getFieldsValue();
    if(option.appointmentTime){
      option.appointmentTime = option.appointmentTime.format('YYYY-MM-DD HH:mm:ss');
    }else{
      Toast.info('请填写预约时间');
      return;
    }
    if(!this.state.hour){
      Toast.info('请填写预约小时数');
      return;
    }else{
      option.hour = parseInt(this.state.hour);
    }
    Ajax({
      url: '/interview/addorder',
      data: Object.assign({
        interviewId
      }, option),
      success: function(result){
        Toast.info('购买成功');
        self.props.onClose();
      },
      error: function(error){
        Toast.info(error||'请求失败');
        self.props.onClose();
      }
    });
  }

  render() {
    const { getFieldProps } = this.props.form;
    return (<List renderHeader={() => (
        <div style={{ position: 'relative' }}>
          购买服务
          <span
            style={{
              position: 'absolute', right: 3, top: -5,
            }}
            onClick={() => this.props.onClose()}
          >
            <Icon type="cross" />
          </span>
        </div>)}
        className="popup-list"
      >
          <DatePicker
            mode="datetime"
            {...getFieldProps('appointmentTime')}
          >
            <List.Item arrow="horizontal">预约时间</List.Item>
          </DatePicker>
        <Item extra={<Stepper min={1} value={this.state.hour}
            onChange={(value)=>{
              this.setState({hour: parseInt(value)})
            }} style={{ width: '100%', minWidth: '2rem' }} showNumber size="small" defaultValue={1} />}>购买数量</Item>
        <List.Item extra={<span style={{color: 'red'}}>{this.state.hour*this.props.data.price}</span>}>
          总价
        </List.Item>
        <TextareaItem
          {...getFieldProps('message')}
          title="留言"
          autoHeight
          labelNumber={5}
        />
        <Button type="primary" style={{margin: '.2rem'}} onClick={() => this.submit()}>确定并支付</Button>
      </List>)
  }
}
const BuyModule = createForm()(buyModuleComp);
